/*
 * MRSTalkApp.java
 */

package mrstalk;

import javax.swing.JDialog;
import javax.swing.JFrame;
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;

/**
 * The main class of the application.
 */
public class MRSTalkApp extends SingleFrameApplication {

    private static Chat chat = null;
    public static ClientWindow clientWindow;

    public static ClientWindow getClientWindow() {
        return clientWindow;
    }

    public static void setClientWindow(ClientWindow clientWindow) {
        MRSTalkApp.clientWindow = clientWindow;
    }

    public static Chat getChat() {
        return chat;
    }

    public static void setChat(Chat chat) {
        MRSTalkApp.chat = chat;
        getApplication().server.interrupt();
        showChatWindow();
    }
    private Thread server;

    private void showClientWindow() {
        clientWindow = new ClientWindow(getApplication());
        getApplication().show(clientWindow);
    }
    
    /**
     * At startup create and show the main frame of the application.
     */
    @Override protected void startup() {
        server = new Thread(new Server());
        server.start();

        showClientWindow();
    }

    /**
     * This method is to initialize the specified window by injecting resources.
     * Windows shown in our application come fully initialized from the GUI
     * builder, so this additional configuration is not needed.
     */
    @Override protected void configureWindow(java.awt.Window root) {
    }

    /**
     * A convenient static getter for the application instance.
     * @return the instance of MRSTalkApp
     */
    public static MRSTalkApp getApplication() {
        return Application.getInstance(MRSTalkApp.class);
    }

    /**
     * ClientWindow method launching the application.
     */
    public static void main(String[] args) {
        launch(MRSTalkApp.class, args);
    }


    public static void showChatWindow() {
        JFrame mainFrame = getApplication().getMainFrame();
        JDialog chatWindow = new ChatWindow(mainFrame, true);
        Thread msgReceiver =
                new Thread(new MsgReceiver(MRSTalkApp.getChat(),
                                          (ChatWindow) chatWindow));
        msgReceiver.start();

        MRSTalkApp.getApplication().show(chatWindow);
    }

}
